<?php

namespace Common\Model;

use Think\Model;

class VersionModel extends Model {

    protected $_validate = array(/* array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]) */
        array('appKey', 'require', '无法生成appKey！'),
        array('device', 'require', '请选择设备！'),
        array('version', 'require', '请确定版本号！'),
    );  // 自动验证定义
    protected $_auto = array(/* array(完成字段1,完成规则,[完成条件,附加规则]) */
        array('addTime', 'time', 1, 'function'),
        array('appID', 'time', 1, 'function'),
        array('isOn', '1', 1),
    );  // 自动完成定义

    /**
     *  获取单个
     */

    public function getVersion($id = null, $where = array(), $field = "*") {
        if ($id > 0) {
            $where['varID'] = $id;
        }

        $result = $this
                ->field($field)
                ->where($where)
                ->find();

        return $result;
    }

    /**
     * 获得列表（带基本查询）
     */
    public function getVersionList($pageNo = 1, $pageSize = 15, $where = array(), $order = array(), $field = "*") {
        $rt = $this
                ->field($field)
                ->where($where)
                ->page("$pageNo,$pageSize")
                ->order($order)
                ->select();

        return $rt;
    }

    public function getVersionListLength($where = array()) {
        return $this->where($where)->count();
    }

    /**
     * 添加单个信息
     * @return type
     */
    public function addVersion($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->add();
        }
        return $rt;
    }

    /**
     * 更新信息(注意$data一定要有主键id,若$data为空，则默认是对$_POST数组处理)
     * @return type
     */
    public function updateVersion($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->save();
        }
        if ($rt) {
            S(C("CACHE_MEM"));
            $temp = array(
                'appKey' => $data['appKey'],
                'status' => intval($data['status']),
                'isOn' => 1,
            );
            S("appID_" . $data['appID'], json_encode($temp));
        }
        return $rt;
    }

    /**
     * 删除
     */
    public function deleteVersion($id) {
        if ($id <= 0) {
            $this->error = "无效ID";
            return false;
        }
        $rt = false;
        $arr = $this->getVersion($id);
        
        if ($arr) {
            $data = array("isOn" => 0, "updateTime" => time());
            $rt = $this->where("verID=$id")->save($data);
            if ($rt) {
                S(C("CACHE_MEM"));
                $temp = array(
                    'appKey' => $arr['appKey'],
                    'status' => intval($arr['status']),
                    'isOn' => 0,
                );
                S("appID_" . $arr['appID'], json_encode($temp));
            }
        } else {
            $this->error = '抱歉，数据不存在';
        }
        return $rt;
    }

}
